package com.deram.ctin.serv.main.api.impl;

import com.deram.ctin.common.bean.UploadResult;
import com.deram.ctin.common.utils.CompareUtils;
import com.deram.ctin.common.utils.DateUtils;
import com.deram.ctin.common.utils.FreeMarkerUtils;
import com.deram.ctin.common.utils.ITextPdfUtils;
import com.deram.ctin.serv.enter.api.EnterInfoApi;
import com.deram.ctin.serv.enter.entity.EnterInfo;
import com.deram.ctin.serv.main.api.EnterDetailApi;
import com.deram.ctin.serv.main.service.EnterDetailService;
import com.deram.ctin.serv.main.vo.EnterDetailVo;
import com.deram.ctin.serv.third.api.QiniuUploadApi;
import com.deram.ctin.serv.third.utils.QiniuUploadUtils;
import freemarker.template.Configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

import java.io.InputStream;

/**
 * @author zhangcm
 * @version 1.0, 2017/9/26
 */
@RestController
public class EnterDetailApiImpl implements EnterDetailApi {

    @Autowired
    private EnterDetailService enterDetailService;
    @Autowired
    private Configuration configuration;
    @Autowired
    private QiniuUploadApi qiniuUploadApi;
    @Autowired
    private EnterInfoApi enterInfoApi;

    @Override
    public EnterDetailVo findDetail(Long id) {
        return enterDetailService.findDetail(id);
    }

    @Override
    public EnterInfo execGeneratePdf(Long id) {
        EnterInfo enterInfo = enterInfoApi.findById(id);
        // 比对更新时间，有更新则重新生成pdf
        if (null != enterInfo.getPdfUpdateDate() && CompareUtils.with(enterInfo.getPdfUpdateDate(), enterInfo.getUpdateDate()) >= 0) {
            return enterInfo;
        }
        String oldUrl = enterInfo.getPdfUrl();
        // 生成pdf
        EnterDetailVo enterDetailResult = enterDetailService.findDetail(id);
        InputStream htmlInputStream = FreeMarkerUtils.createInputStream(configuration, "enterInfo.ftl", enterDetailResult);
        InputStream inCssFile = EnterDetailApiImpl.class.getResourceAsStream("/ftl/css/pdf.css");
        String resourcesRootPath = EnterDetailApiImpl.class.getResource("/ftl/").getFile();
        InputStream pdfInputStream = ITextPdfUtils.create(htmlInputStream, inCssFile, resourcesRootPath);
        String name = enterInfo.getName() + "." + DateUtils.getNowLong() + ".pdf";
        UploadResult uploadResult = QiniuUploadUtils.upload(qiniuUploadApi.getConfig(), name, pdfInputStream);
        enterInfo.setPdfUrl(uploadResult.getUrl());
        enterInfo.setPdfUpdateDate(DateUtils.getNow());
        enterInfoApi.save(enterInfo);
        // 删除原先的url
        qiniuUploadApi.delete(oldUrl);
        return enterInfo;
    }
}
